package array

// Push 向后添加元素
func Push[T any](array []T, elements ...T) []T {
	return append(array, elements...)
}

// Pop 取出最后一个元素
func Pop[T any](array []T) (T, []T) {
	var zero T
	if len(array) == 0 {
		return zero, array
	}
	return array[len(array)-1], array[:len(array)-1]
}

// Shift 取出第一个元素
func Shift[T any](array []T) (T, []T) {
	var zero T
	if len(array) == 0 {
		return zero, array
	}
	return array[0], array[1:]
}

// Unshift 向前添加元素
func Unshift[T any](array []T, elements ...T) []T {
	return append(elements, array...)
}

// Reverse 翻转数组
func Reverse[T any](array []T) []T {
	for i, j := 0, len(array)-1; i < j; i, j = i+1, j-1 {
		array[i], array[j] = array[j], array[i]
	}
	return array
}

// Slice 截取数组
func Slice[T any](array []T, start, end int) []T {
	if start < 0 {
		start = 0
	}
	if end > len(array) {
		end = len(array)
	}
	return array[start:end]
}

// Splice 删除、插入、替换元素
func Splice[T any](array []T, start, deleteCount int, elements ...T) []T {
	if start < 0 {
		start = 0
	}
	if start > len(array) {
		start = len(array)
	}
	if deleteCount < 0 {
		deleteCount = 0
	}
	if deleteCount > len(array)-start {
		deleteCount = len(array) - start
	}
	result := make([]T, 0, len(array)-deleteCount+len(elements))

	// 1. copy array[0:start]
	for i := 0; i < start; i++ {
		result = append(result, array[i])
	}

	// 2. copy elements
	for i := 0; i < len(elements); i++ {
		result = append(result, elements[i])
	}

	// 3. copy array[start+deleteCount:]
	for i := start + deleteCount; i < len(array); i++ {
		result = append(result, array[i])
	}
	return result
}

// Concat 合并数组
func Concat[T any](arrays ...[]T) []T {
	var result []T
	for _, array := range arrays {
		result = append(result, array...)
	}
	return result
}

// Sort 排序数组
func Sort[T any](array []T, comparator func(T, T) int) []T {
	for i := 0; i < len(array); i++ {
		for j := i + 1; j < len(array); j++ {
			if comparator(array[i], array[j]) > 0 {
				array[i], array[j] = array[j], array[i]
			}
		}
	}
	return array
}
